import store from '@/store'
import router from './index'
import { session } from '@/utils/jcore/storage'
import NProgress from '@/config/nprogress'
import { initDynamicRouter } from './modules/dynamicRouter'
import { LOGIN_URL, ROUTER_WHITE_LIST } from '@/config/config'

router.beforeEach(async (to, from, next) => {
  NProgress.start()

  const token = session.get('token')
  // 没有token
  if (!token) {
    // 白名单页面放行
    if (ROUTER_WHITE_LIST.includes(to.path)) return next()
    // 其他页面重定向到登录页
    return next(LOGIN_URL)
  }

  // 进入登录页重定向到首页
  if (to.path == LOGIN_URL) return next('/')
  // 添加动态路由
  if (!store.getters.menuList.length) {
    await initDynamicRouter()
    // 动态路由添加完成此时需重新加载否则页面白屏
    return next({ ...to, replace: true })
  }

  next()
})

/**路由跳转结束 */
router.afterEach(() => {
  NProgress.done()
})

/**路由跳转错误 */
router.onError((error) => {
  NProgress.done()
  console.warn('路由错误', error.message)
})
